package rabbitMQ.rpc;

import com.rabbitmq.client.*;
import rabbitMQ.common.Common;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;

public class Client {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {

        //1. 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2. 设置参数
        factory.setHost(Common.HOST);//ip
        factory.setPort(Common.PORT);//端口号
        factory.setVirtualHost(Common.VIRTUALHOST);//虚拟机名称
        factory.setUsername(Common.USERNAME);//用户名
        factory.setPassword(Common.PASSWORD);//密码
        //3. 创建连接connection
        Connection connection = factory.newConnection();

        //创建channel
        Channel channel = connection.createChannel();
        //发送请求:
        //声明队列
        channel.queueDeclare(Common.RPC_REQUEST_QUEUE, true, false, false, null);
        channel.queueDeclare(Common.RPC_RESPONSE_QUEUE, true, false, false, null);
        //定义回调队列
        String replyQueueName = Common.RPC_RESPONSE_QUEUE;
        //本次请求的唯一标识
        String corrId = UUID.randomUUID().toString();
        //生成发送消息的属性
        AMQP.BasicProperties props = new AMQP.BasicProperties
                .Builder()
                .correlationId(corrId)
                .replyTo(replyQueueName)
                .build();
        //通过内置交换机, 发送消息
        String message = "hello, rpc......";
        channel.basicPublish("", Common.RPC_REQUEST_QUEUE, props, message.getBytes(StandardCharsets.UTF_8));

        //接收响应:
        //使用阻塞队列来存储回调结果, 避免了客户端反复访问队列
        final BlockingQueue<String> response = new ArrayBlockingQueue<>(1);

        //接收服务器的响应
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接收到消息: " + new String(body));
                //如果唯一标识正确, 放在阻塞队列中
                if(properties.getCorrelationId().equals(corrId)){
                    response.offer(new String(body));
                }
            }
        };
        channel.basicConsume(replyQueueName, true, consumer);
        //获取回调的结果
        String result = response.take();
        System.out.println("[RPCClient] Result: " + result);
    }
}
